package mathFrame

import javafx.{event => jfxe}

import JimParsers._

import scalafx.Includes._
import scalafx.application.JFXApp
import scalafx.scene.Scene
import scalafx.scene.control._
import scalafx.scene.layout._
import scalafx.stage.Stage

object Main extends JFXApp {
  Trigonometry.init
  Arithmetic.init
  val x = new Parameter("x")
  stage = new Stage {
    title = "Mategráfica"
  }
  val scene = new Scene(400, 400)
  stage.scene = scene
  val content = new BorderPane
  scene.content = content
  val plotter = new Plotter2D
  val label = new Label {
    text = "f(x) = "
  }
  val edit: TextField = new TextField {
    prefWidth = 200
  }
  val actionHandler = new jfxe.EventHandler[jfxe.ActionEvent] {
    def handle(e: jfxe.ActionEvent) = {
      JimParsers.parseExpr(edit.getText, x) match {
        case Success(tree, _) => plotter.func = new UserFunction1P("", x, tree)
        case Failure(msg, _) => {
            println(msg)
            plotter.func = NoValue
        }
      }
      plotter.regenerate
    }
  }
  edit.onAction = actionHandler
  val parse = new Button {
    text = "Parse"
    onAction = actionHandler
  }
  val top =  new HBox {
    content += label
    content += edit
    content += parse
  }
  content top = top
  content center = plotter
}

object Maint {
  def main(args: Array[String]): Unit = {
    Trigonometry.init
    Arithmetic.init
    JimParsers.testExpr("123")
    JimParsers.testExpr("12 + 34")
    JimParsers.testExpr("2 - 1")
    JimParsers.testExpr("1 + 2 + 3 - 4")
    JimParsers.testExpr("3 + 4 * 5")
    JimParsers.testExpr("(3 + 4) * 5")
    JimParsers.testExpr("3*-(2+2)")
    JimParsers.testExpr("123.456")
    JimParsers.testExpr("1.2+3")
    JimParsers.testExpr("5e-1 + 2")
    JimParsers.test("const e = 2.71828183")
    JimParsers.test("var x")
    JimParsers.test("var y = 1")
    JimParsers.testFail("const x = 3")
    JimParsers.test("def f(x) = sin(x)")
    JimParsers.testExpr("sin(pi/2)")
    JimParsers.test("def g(x) = f(2*x)")
    JimParsers.testExpr("g(2)")
  }
}

